import axios from 'axios'
import Session from '@/core/session'
import rspFunc from '@/core/request/response'

const Http = axios.create({
  baseURL: '/api', // 因为我本地做了反向代理
  timeout: 300000,
  responseType: 'json',
  withCredentials: true, // 是否允许带cookie这些
  headers: {
    'Content-Type': 'multipart/form-data;charset=utf-8'
  }
})

var call = {}

// POST传参序列化(添加请求拦截器)
Http.interceptors.request.use(
  config => {
    // 若是有做鉴权token , 就给头部带上token
    // 若是需要跨站点,存放到 cookie 会好一点,限制也没那么多,有些浏览环境限制了 localstorage 的使用
    // 这里localStorage一般是请求成功后我们自行写入到本地的,  因为你放在vuex刷新就没了
    // 一些必要的数据写入本地,优先从本地读取
    config.onUploadProgress = (progressEvent) => {
      if (progressEvent.lengthComputable) {
        // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
        // 如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
        call.progressEvent(progressEvent)
      }
    }
    // 在发送请求之前做某件事
    if (Session.jsessionid()) {
      config.headers.Authorization = Session.jsessionid()
    }
    return config
  },
  error => {
    return Promise.reject(error.data.error.message)
  }
)

// 返回状态判断(添加响应拦截器)
Http.interceptors.response.use(
  response => {
    return rspFunc.response(response)
  },
  error => {
    return rspFunc.error(error)
  }
)

function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    Http
      .post(url, data)
      .then(response => {
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export function upload (
  url,
  data = {},
  operation = {
    // 一开始的回调
    begin: () => { },
    // 成功的回调
    callback: () => { },
    // 失败的回调
    falisback: () => { },
    // 完成的回调
    complete: () => { },
    // 上传过程中的回调事件
    progressEvent: () => { }
  }
) {
  if (operation.progressEvent && typeof operation.progressEvent === 'function') {
    call.progressEvent = event => {
      operation.progressEvent(event)
    }
  }
  if (operation.begin && typeof operation.begin === 'function') {
    operation.begin()
  }
  return post(url, data).then(
    response => {
      if (operation.callback && typeof operation.callback === 'function') {
        operation.callback(response)
      }
      if (operation.complete && typeof operation.complete === 'function') {
        operation.complete(response)
      }
    },
    error => {
      if (operation.falisback && typeof operation.falisback === 'function') {
        operation.falisback(error)
      }
      if (operation.complete && typeof operation.complete === 'function') {
        operation.complete(error)
      }
      console.error(error)
    }
  )
}
